package com.wzm.service.impl;

import com.wzm.domain.Move;
import com.wzm.domain.UserMove;
import com.wzm.mapper.MoveMapper;
import com.wzm.service.MoveService;
import com.wzm.util.Ajaxresult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class MoveServiceImpl implements MoveService {
    @Autowired
    private MoveMapper moveMapper;

    @Override
    public List<Move> findAll() {
        return moveMapper.findAll();
    }

    @Override
    public Move findById(Long id) {
        return moveMapper.findById(id);
    }

    @Override
    @Transactional
    public Ajaxresult buyById(UserMove userMove) {
        Move move = moveMapper.findById(userMove.getMovie_ticket_id());
        move.setStock(move.getStock() - 1);
        moveMapper.update(move);
        userMove.setStatus(0);
        moveMapper.add(userMove);
        return new Ajaxresult(true, "购买成功", move.getPrice());
    }

    @Override
    public Ajaxresult sendTicket(UserMove userMove) {
        List<Move> all = moveMapper.findAll();
        int size = all.size();
        Random random = new Random();
        Long aLong = new Long(random.nextInt(size+1));
        Move byId = moveMapper.findById(aLong);
        if (byId == null) {
            return new Ajaxresult(false, "很遗憾", "您未抽中免费票");
        }
        userMove.setMovie_ticket_id(aLong);
        moveMapper.add(userMove);
        Move move = moveMapper.findById(aLong);
        move.setStock(move.getStock()-1);
        moveMapper.update(move);
        return new Ajaxresult();
    }

    @Override
    public Ajaxresult watch(Long id) {
        List<UserMove> userMove = moveMapper.findStatusByTicketId(id);
        Move move = moveMapper.findById(id);

        if(move.getStart_time().after(new Date())){
            return new Ajaxresult(false, "电影还未开始", "请等电影开始再来");
        }
        if(new Date().after(move.getEnd_time())){
            return new Ajaxresult(false, "电影已结束", "请等下次再来");
        }
        if (userMove.size()==0) {
            return new Ajaxresult(false, "您未购买", "请重新购票");
        }
        for (UserMove um : userMove) {
            if (um.getMovie_ticket_id().equals(id) && um.getStatus()==1) {
                moveMapper.del(um.getMovie_ticket_id(),um.getStatus());
                return new Ajaxresult(false, "已过期", "请重新购票");
            }else if(um.getMovie_ticket_id().equals(id) && um.getStatus()==0){
                um.setStatus(1);
                moveMapper.updateUserMove(um);
            }
        }
        return new Ajaxresult(true, "电影观看结束", "祝您生活愉快");
    }
}
